package com.imedical.util;


import com.imedical.enums.CoreConstant;
import com.imedical.exception.DataException;

import java.awt.Color;
import java.awt.Font;
import java.io.IOException;
import java.util.HashMap;

import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import lombok.extern.slf4j.Slf4j;

/**
 * @author zhongyj <1126834403@qq.com><br/>
 * @date 2022/5/12
 */
@Slf4j
public class R extends HashMap<String, Object> {

    private static final Integer FAIL = 300;

    private static R r = new R();

    private static final String CODE = "code";


    private static final String MSG = "msg";

    private static final String DATA = "data";


    public static R failed() {
        r.put(CODE, FAIL);
        r.put(MSG, "失败");
        r.put(DATA, null);
        return r;
    }

    public static R failed(String msg) {
        r.put(CODE, FAIL);
        r.put(MSG, msg);
        r.put(DATA, null);
        return r;
    }

    public static R failed(int code, String msg) {
        r.put(CODE, code);
        r.put(MSG, msg);
        r.put(DATA, null);
        return r;
    }

    /**
     * 返回文件流
     *
     * @param filePath 文件路径
     */
    public static void makeResponse(String filePath) {
        if (FileUtil.isFile(filePath)) {
            makeResponse(HttpContextUtil.getResponse(), FileUtil.getMimeType(filePath), HttpStatus.HTTP_OK, FileUtil.readBytes(filePath));
            FileUtil.del(filePath);
        } else {
            makeImageAndResponse(StrUtil.format("【{}】不是一个文件", filePath));
        }
    }

    /**
     * 返回流数据
     *
     * @param response    HttpServletResponse
     * @param contentType String
     * @param status      int
     * @param value       byte[]
     */
    public static void makeResponse(HttpServletResponse response, String contentType,
                                    int status, byte[] value) {
        response.setContentType(contentType + ";charset=UTF-8");
        response.setStatus(status);
        response.setCharacterEncoding("UTF-8");
        try {
            response.getOutputStream().write(value);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw new DataException(e.getMessage());
        }
    }

    /**
     * 生成图片返回
     *
     * @param imageText 图片展示信息
     */
    public static void makeImageAndResponse(String imageText) {
        String tmpPngPath = CoreConstant.TMP_FILE_DIR + UUID.fastUUID() + ".png";
        ImgUtil.createImage(imageText, new Font("宋体", Font.PLAIN, 18), Color.WHITE, Color.BLACK, ImgUtil.getImageOutputStream(FileUtil.newFile(tmpPngPath)));
        makeResponse(HttpContextUtil.getResponse(), FileUtil.getMimeType(tmpPngPath), HttpStatus.HTTP_OK, FileUtil.readBytes(tmpPngPath));
    }
}











